package middleware

import (
	"context"
	"net/http"

	"github.com/go-kit/kit/endpoint"
	"github.com/go-playground/validator/v10"
	"xincan.com.cn/tarot-go-framework/global"
	"xincan.com.cn/tarot-go-framework/utils/response"
)

// GlobalValidationEndPoint
// Title    		GlobalValidationEndPoint
// Description   	"全局验证器(适合使用结构体)"
// Param    		dto interface{}					"对象"
// Auth      		alittlexincan@163.com         	"时间（2024/07/22 11:36）"
// Return    		endpoint.Endpoint				"返回值"
func GlobalValidationEndPoint(dto interface{}) endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		if err := global.Valid.Validate.Struct(dto); err != nil {
			for _, err := range err.(validator.ValidationErrors) {
				return response.NewError(http.StatusUnprocessableEntity, err.Translate(*global.Valid.Trans)), nil
			}
			return nil, err
		}
		return request, nil
	}

}

// GlobalValidationMiddleware
// Title    		GlobalValidationMiddleware
// Description   	"全局验证器(适合使用对象)"
// Param    		dto interface{}					"对象"
// Auth      		alittlexincan@163.com         	"时间（2024/07/22 11:36）"
// Return    		endpoint.Endpoint				"返回值"
func GlobalValidationMiddleware(dto interface{}) endpoint.Middleware {
	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (interface{}, error) {
			if err := global.Valid.Validate.Struct(dto); err != nil {
				for _, filedErr := range err.(validator.ValidationErrors) {
					if filedErr.Tag() == "v-password" {
						return response.NewError(http.StatusUnprocessableEntity, "密码格式不正确, 必须同时包含至少大写字母小写字母和数字各一个"), nil
					}
					return response.NewError(http.StatusUnprocessableEntity, filedErr.Translate(*global.Valid.Trans)), nil
				}
				return nil, err
			}
			return next(ctx, request)
		}
	}
}

// GlobalValidationValueSetMiddleware
// Title    		GlobalValidationValueSetMiddleware
// Description   	"全局验证器(适合使用值)"
// Param    		label string					"错误信息标签"
// Param    		value string					"值"
// Param    		valid string					"验证规则"
// Auth      		alittlexincan@163.com         	"时间（2024/07/22 11:36）"
// Return    		endpoint.Endpoint				"返回值"
func GlobalValidationValueSetMiddleware(label string, value interface{}, valid string) endpoint.Middleware {
	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (interface{}, error) {
			if err := global.Valid.Validate.Var(value, valid); err != nil {
				for _, err := range err.(validator.ValidationErrors) {
					return response.NewError(http.StatusUnprocessableEntity, label+""+err.Translate(*global.Valid.Trans)), nil
				}
				return nil, err
			}
			return next(ctx, request)
		}
	}
}
